package com.csii.modules.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csii.core.annotation.Dict;
import com.csii.core.constant.CacheConstant;
import com.csii.core.constant.CommonConstant;
import com.csii.core.constant.SyncDictType;
import com.csii.core.system.vo.DictModel;
import com.csii.core.system.vo.DictQuery;
import com.csii.core.system.vo.DictRedisHash;
import com.csii.core.system.vo.SyncDictVo;
import com.csii.core.util.oConvertUtils;
import com.csii.galaxy.studio.entity.SysDict;
import com.csii.galaxy.studio.entity.SysDictItem;
import com.csii.modules.system.mapper.SysDictItemMapper;
import com.csii.modules.system.mapper.SysDictMapper;
import com.csii.modules.system.model.TreeSelectModel;
import lombok.extern.slf4j.Slf4j;
import com.csii.modules.system.service.ISysDictService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @Author zhangweijian
 * @since 2018-12-28
 */
@Service
@Slf4j
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements ISysDictService {

    @Autowired
    private SysDictMapper sysDictMapper;
    @Autowired
    private SysDictItemMapper sysDictItemMapper;

    @Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private JdbcTemplate jdbcTemplate;

    private final String DICT_REGISTER_LIST = "DICT_REGISTER_LIST";

    private final String ALL_DICT_LIST = "ALL_DICT_LIST";

    private final long outOfDate = 1;

	@Value("${dict.isService:false}")
	private boolean isDictService;

	/**
	 * 通过查询指定code 获取字典
	 * @param code
	 * @return
	 */
	@Override
	public List<DictModel> queryDictItemsByCode(String code) {
		log.info("无缓存dictCache的时候调用这里！");
		return sysDictMapper.queryDictItemsByCode(code);
	}

	@Override
	public Map<String, List<DictModel>> queryAllDictItems() {
		Map<String, List<DictModel>> res = new HashMap<String, List<DictModel>>();
		List<SysDict> ls = sysDictMapper.selectList(null);
		LambdaQueryWrapper<SysDictItem> queryWrapper = new LambdaQueryWrapper<SysDictItem>();
		queryWrapper.eq(SysDictItem::getStatus, 1);
		queryWrapper.orderByAsc(SysDictItem::getSortOrder);
		List<SysDictItem> sysDictItemList = sysDictItemMapper.selectList(queryWrapper);

		for (SysDict d : ls) {
			List<DictModel> dictModelList = sysDictItemList.stream().filter(s -> d.getId().equals(s.getDictId())).map(item -> {
				DictModel dictModel = new DictModel();
				dictModel.setText(item.getItemText());
				dictModel.setValue(item.getItemValue());
				return dictModel;
			}).collect(Collectors.toList());
			res.put(d.getDictCode(), dictModelList);
		}
		log.info("-------登录加载系统字典-----" + res.toString());
		return res;
	}

	/**
	 * 通过查询指定code 获取字典值text
	 * @param code
	 * @param key
	 * @return
	 */

	@Override
	public String queryDictTextByKey(String code, String key) {
		log.info("无缓存dictText的时候调用这里！");
		return sysDictMapper.queryDictTextByKey(code, key);
	}

	/**
	 * 通过查询指定table的 text code 获取字典
	 * dictTableCache采用redis缓存有效期10分钟
	 * @param table
	 * @param text
	 * @param code
	 * @return
	 */
	@Override
	public List<DictModel> queryTableDictItemsByCode(String table, String text, String code) {
		log.info("无缓存dictTableList的时候调用这里！");
		//代码扫描sql注入问题 return  sysDictMapper.queryTableDictItemsByCode(table,text,code);
		String sql = "select " + text +  " as text ," + code + " as value from " + table;
		List<DictModel> listDictModel = jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper<>(DictModel.class));
		return listDictModel;
	}

	@Override
	public List<DictModel> queryTableDictItemsByCodeAndFilter(String table, String text, String code, String filterSql) {
		log.info("无缓存dictTableList的时候调用这里！");
		//代码扫描sql注入问题 return  sysDictMapper.queryTableDictItemsByCodeAndFilter(table,text,code,filterSql);
		String sql = "select "+ text + " as text ," + code + " as value from " + table;
		if (!StringUtils.isEmpty(filterSql)) {
			sql = sql + " where " + filterSql;
		}
		List<DictModel> listDictModel = jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper<>(DictModel.class));
		return listDictModel;
	}

	/**
	 * 通过查询指定table的 text code 获取字典值text
	 * dictTableCache采用redis缓存有效期10分钟
	 * @param table
	 * @param text
	 * @param code
	 * @param key
	 * @return
	 */
	@Override
	public String queryTableDictTextByKey(String table,String text,String code, String key) {
		log.info("无缓存dictTable的时候调用这里！");
		//sql注入 return sysDictMapper.queryTableDictTextByKey(table,text,code,key);
		String sql = "select "+ text +" as text from "+ table +" where " + code + " = ?;";
		String result =  jdbcTemplate.queryForObject(sql, String.class, new Object[]{key});
		return result;
	}

	/**
	 * 通过查询指定table的 text code 获取字典，包含text和value
	 * dictTableCache采用redis缓存有效期10分钟
	 * @param table
	 * @param text
	 * @param code
	 * @param keys (逗号分隔)
	 * @return
	 */
	@Override
	public List<String> queryTableDictByKeys(String table, String text, String code, String keys) {
		if(oConvertUtils.isEmpty(keys)){
			return null;
		}
		String[] keyArray = keys.split(",");
		/*sql注入
		List<DictModel> dicts = sysDictMapper.queryTableDictByKeys(table, text, code, keyArray);*/
		String sql = "select " + text + " as text ," + code + " as value from " + table + " where "+ code + " in ( :keys )";
		NamedParameterJdbcTemplate jdbc = new NamedParameterJdbcTemplate(jdbcTemplate);
		List<String> keyList = Arrays.asList(keyArray);
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("keys",keyList);
		List<DictModel> dicts = jdbc.queryForList(sql,paramMap,DictModel.class);
		List<String> texts = new ArrayList<>(dicts.size());
		// 查询出来的顺序可能是乱的，需要排个序
		for (String key : keyArray) {
			for (DictModel dict : dicts) {
				if (key.equals(dict.getValue())) {
					texts.add(dict.getText());
					break;
				}
			}
		}
		return texts;
	}

    /**
     * 根据字典类型id删除关联表中其对应的数据
     */
    @Override
    public boolean deleteByDictId(SysDict sysDict) {
        sysDict.setDelFlag(CommonConstant.DEL_FLAG_1);
        return  this.updateById(sysDict);
    }

    @Override
    @Transactional
    public Integer saveMain(SysDict sysDict, List<SysDictItem> sysDictItemList) {
		int insert=0;
    	try{
			 insert = sysDictMapper.insert(sysDict);
			if (sysDictItemList != null) {
				for (SysDictItem entity : sysDictItemList) {
					entity.setDictId(sysDict.getId());
					entity.setStatus(1);
					sysDictItemMapper.insert(entity);
				}
			}
		}catch(Exception e){
			return insert;
		}
		return insert;
    }

	@Override
	public List<DictModel> queryAllDepartBackDictModel() {
		return baseMapper.queryAllDepartBackDictModel();
	}

	@Override
	public List<DictModel> queryAllUserBackDictModel() {
		return baseMapper.queryAllUserBackDictModel();
	}

	@Override
	public List<DictModel> queryTableDictItems(String table, String text, String code, String keyword) {
		return baseMapper.queryTableDictItems(table, text, code, "%"+keyword+"%");
	}

	@Override
	public List<TreeSelectModel> queryTreeList(Map<String, String> query, String table, String text, String code, String pidField, String pid, String hasChildField) {
		return baseMapper.queryTreeList(query,table, text, code, pidField, pid,hasChildField);
	}

	@Override
	public void deleteOneDictPhysically(String id) {
		this.baseMapper.deleteOneById(id);
		this.sysDictItemMapper.delete(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getDictId,id));
	}

	@Override
	public void updateDictDelFlag(int delFlag, String id) {
		baseMapper.updateDictDelFlag(delFlag,id);
	}

	@Override
	public List<SysDict> queryDeleteList() {
		return baseMapper.queryDeleteList();
	}

	@Override
	public List<DictModel> queryDictTablePageList(DictQuery query, int pageSize, int pageNo) {
		Page page = new Page(pageNo,pageSize,false);
		Page<DictModel> pageList = baseMapper.queryDictTablePageList(page, query);
		return pageList.getRecords();
	}

	@Override
	public SyncDictVo syncDict(String redisListKey,int lastSyncResult) {
    	//如果是主机的话 , 直接查询全部
    	if (isDictService){
    		return syncAll();
		}
		List<Object> dictRegisterList = redisTemplate.opsForList().range(DICT_REGISTER_LIST, 0, -1);
		if (CollUtil.isEmpty(dictRegisterList) || dictRegisterList.indexOf(redisListKey) == -1){
			redisTemplate.opsForList().leftPush(DICT_REGISTER_LIST,redisListKey);
			redisTemplate.delete(redisListKey);
			//全量
			return syncAll();
		}
		//TODO 是否增加无用注册key清除

		//判断上次同步是否是失败的, 是失败的就全量
		if (lastSyncResult == -1){
			redisTemplate.delete(redisListKey);
			//全量
			return syncAll();
		}

		List<DictRedisHash> incrementDictList = redisTemplate.opsForList().range(redisListKey, 0, -1);
		if (CollUtil.isNotEmpty(incrementDictList)) {
			//增量
			SyncDictVo syncDictVo = new SyncDictVo();
			syncDictVo.setSyncType(SyncDictType.ADD);
			syncDictVo.setList(incrementDictList);
			redisTemplate.delete(redisListKey);
			return syncDictVo;
		}

		//全量
		return syncAll();
	}

	private SyncDictVo syncAll(){
		SyncDictVo syncDictVo = new SyncDictVo();
		syncDictVo.setSyncType(SyncDictType.ALL);
		syncDictVo.setList(queryAllResultDictRedisHash());
		return syncDictVo;
	}


	//使用加锁双重验证来避免并发请求时 重复请求数据库
	private List<DictRedisHash> queryAllResultDictRedisHash(){
		List<DictRedisHash> dictRedisHashList = (List<DictRedisHash>) redisTemplate.opsForValue().get(ALL_DICT_LIST);
		if (dictRedisHashList == null){
			synchronized (this){
				dictRedisHashList = (List<DictRedisHash>) redisTemplate.opsForValue().get(ALL_DICT_LIST);
				if (dictRedisHashList == null){
					dictRedisHashList = sysDictMapper.queryAllResultDictRedisHash();
					redisTemplate.opsForValue().set(ALL_DICT_LIST,dictRedisHashList,outOfDate,TimeUnit.DAYS);
				}
			}
		}
		return dictRedisHashList;
	}
}
